package mylab.starters.mybatis.config;

import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import lombok.extern.slf4j.Slf4j;
import mylab.starters.mybatis.config.tenant.TenantMode;
import mylab.starters.mybatis.support.mixedSource.TenantDataSourceProvider;
import mylab.starters.mybatis.support.mixedSource.TenantDataSourceService;
import mylab.starters.mybatis.support.mixedSource.impl.TenantDataSourceServiceImpl;
import mylab.starters.mybatis.support.tenant.TenantDatasourceModeInterceptor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 多数据源配置
 * 1、支持baimidou dynamicDataSource 原生用法，参见 dynamic-datasource-spring-boot-starter
 * 2、扩展支持租户多数据源模式（租户数据源配置信息存储在master库）
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(DbPluginAutoConfiguration.class)
@ConditionalOnClass({DynamicDataSourceAutoConfiguration.class})
public class MixedDataSourceAutoConfiguration {

    /**
     * 动态数据源提供者
     *
     * @return 动态数据源提供者
     */
    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider(DynamicDataSourceProperties dynamicDataSourceProperties,
                                                               DbProperties dbProperties) {
        return new TenantDataSourceProvider(dynamicDataSourceProperties, dbProperties);
    }

    /**
     * 动态数据源管理服务
     *
     * @return 多数据源管理服务
     */
    @Bean
    public TenantDataSourceService dynamicDataSourceService() {
        return new TenantDataSourceServiceImpl();
    }

    /**
     * 租户独立数据源模式插件
     *
     * @return 租户独立数据源模式插件
     */
    @Bean
    @ConditionalOnProperty(value = DbProperties.PREFIX + ".tenant.mode", havingValue = "DATASOURCE")
    public TenantDatasourceModeInterceptor tenantDatasourceModeInterceptor() {
        log.info("租户模式:{}", TenantMode.DATASOURCE.name());
        return new TenantDatasourceModeInterceptor();
    }

}
